﻿using System;
using System.Collections.Generic;
using System.Text;
using Eqwww.Data;
using Eqwww.Code;
using Eqwww.Domain.Models.SystemSecurity;
using Microsoft.EntityFrameworkCore;
using Eqwww.Domain;
using System.Linq;
using Microsoft.Extensions.Configuration;

namespace Eqwww.App.SystemSecurity
{
    public class DbBackupApp
    {
        private ApplicationDbContext _context;
        private IModelHandler _modelHandler;
        private IConfiguration _configuration;
        public DbBackupApp(ApplicationDbContext context, IModelHandler modelHandler
            ,IConfiguration configuration)
        {
            _context = context;
            _modelHandler = modelHandler;
            _configuration = configuration;
        }

        public string LoadDefaultDatabaseName()
        {
            try
            {
                var connstr = _configuration.GetConnectionString("DefaultConnection");
                var dbname = Common.RegexStr(connstr, @"Catalog=(?<dbname>[\s\S]+?);", "dbname");
                return dbname;
            }
            catch
            {
                return string.Empty;
            }
        }

        public ModelResult Create(DbBackupModel model)
        {
            var sql = string.Format("backup database {0} to disk ='{1}'", model.DbName, model.FilePath);
            var conn = _context.Database.GetDbConnection();
            conn.Open();
            using(var command = conn.CreateCommand())
            {
                command.CommandText = sql;
                command.ExecuteNonQuery();
            }
            conn.Close();
            //_context.Database.ExecuteSqlCommand(sql);
            model.FileSize = Common.GetFileSizeStr(FileHelper.GetFileSize(model.FilePath));
            model.FilePath = "/upload/dbbackup/" + model.FileName;
            model.BackupTime = DateTime.Now;
            _modelHandler.Create(model);
            _context.Add(model);
            _context.SaveChanges();
            return Code.Common.SuccessResult();
        }

        public IList<DbBackupModel> GetList(Pagination pagination)
        {
            var exp = ExtLinq.True<DbBackupModel>();
            exp = exp.And(x => x.DeleteMark != true);
            var data = _context.FindList(exp, pagination);
            return data;
        }

        public DbBackupModel Get(string id)
        {
            var model = _context.Set<DbBackupModel>().AsNoTracking().FirstOrDefault(x => x.DeleteMark != true && x.Id == id);
            return model;
        }

        public ModelResult Delete(string id)
        {
            var model = Get(id);

            FileHelper.DeleteFiles("/wwwroot" + model.FilePath, false);
            _modelHandler.Delete(model);
            _context.Update(model);
            _context.SaveChanges();
            return Common.SuccessResult();
        }
    }
}
